package com.mokairui.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @Description
 * @Author Mokairui
 * @Since 2021/10/29
 */
@Slf4j(topic = "c.EventLoopClient")
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        // 带有 Future, Promise 的类型都是和 异步方法配套使用, 用来处理结果
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // 连接服务器, 异步非阻塞 main 发起调用, 真正执行 connect 是 nio 线程
                .connect(new InetSocketAddress("localhost", 8080));

        // 1. 等待成功连接后再获取通道, 同步处理结果 ChannelFuture.sync() 同步调用
//        channelFuture.sync(); // 阻塞住当前线程, 知道nio线程连接建立完毕
//        Channel channel = channelFuture.channel();
//        log.debug("{}", channel);
//        channel.writeAndFlush("hello, world");

        System.out.println("");

        // 2. 使用 addListener(回调对象) 方法异步处理结果 异步调用
        channelFuture.addListener(new ChannelFutureListener() {
            // 在 nio 线程连接建立好之后, 会调用 operationComplete
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                log.debug("{}", channel);
                channel.writeAndFlush("hello, world");
            }
        });
    }
}
